<template>
  <div>
    <h-table-list
      border
      type="local"
      :data="system_field.records"
      :columns="columns"
      :show-pagination="false"
      :page-sizes="[30, 40]"
      :form-options="formOptions"
    >
      <!-- <ListOpearteButton /> -->
      <template slot="slot-fieldName" slot-scope="scope">
        <span v-if="scope.$index < 12">{{ scope.row.fieldName }}</span>
        <el-input
          v-if="scope.$index > 11"
          :ref="system_field.records[scope.$index].fieldName"
          v-model="system_field.records[scope.$index].fieldName"
          placeholder="请输入内容"
          maxlength="20"
          :class="{ 'input-selected': false }"
        />
      </template>
      <template slot="slot-fieldType" slot-scope="scope">
        <span v-if="scope.$index < 12">-</span>
        <el-select
          :disabled="
            system_field.records[scope.$index].disabled != 1 ? true : false
          "
          v-if="scope.$index > 11"
          :ref="system_field.records[scope.$index].fieldType"
          v-model="system_field.records[scope.$index].fieldType"
          placeholder="请选择"
        >
          <el-option
            v-for="item in selectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template>
      <template slot="slot-fieldRuleType" slot-scope="scope">
        <span v-if="scope.$index < 12">-</span>
        <!--根据字段类型的动态变化字段规则字段模式,虽然功能很鸡肋-0- -->
        <!--单行纯数字（整数\小数）长度-->
        <el-input
          v-if="
            scope.$index > 11 &&
            system_field.records[scope.$index].fieldType != 'input' &&
            system_field.records[scope.$index].fieldType != 'select1' &&
            system_field.records[scope.$index].fieldType != 'datePicker1' &&
            system_field.records[scope.$index].fieldType != 'organization'
          "
          :ref="system_field.records[scope.$index].fieldRuleType"
          v-model="system_field.records[scope.$index].fieldRuleType"
          type="number"
          placeholder="请输入内容"
          oninput="if(value>10) {return value=10} if(value<0){return value=-value} if(value==0){return value=null}"
        >
          <template slot="prepend">长度 </template>
          <template slot="append">位</template>
        </el-input>
        <!--组织架构选择框-->
        <span
          v-if="
            scope.$index > 11 &&
            system_field.records[scope.$index].fieldType == 'organization'
          "
          >-
        </span>

        <!--单行文本框长度-->
        <el-input
          v-if="
            scope.$index > 11 &&
            system_field.records[scope.$index].fieldType == 'input'
          "
          :ref="system_field.records[scope.$index].fieldRuleType"
          v-model="system_field.records[scope.$index].fieldRuleType"
          type="number"
          placeholder="请输入内容"
          oninput="if(value>100) {return value=100} if(value<0){return value=-value} if(value==0){return value=null}"
        >
          <template slot="prepend">长度 </template>
          <template slot="append">位</template>
        </el-input>

        <!--时间选择-->
        <el-select
          v-if="
            scope.$index > 11 &&
            system_field.records[scope.$index].fieldType == 'datePicker1'
          "
          :ref="system_field.records[scope.$index].fieldType"
          v-model="system_field.records[scope.$index].fieldRuleType"
          placeholder="请选择"
        >
          <el-option
            v-for="item in selectDateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-input
          v-if="
            scope.$index > 11 &&
            system_field.records[scope.$index].fieldType == 'select1'
          "
          :ref="system_field.records[scope.$index].fieldRuleType"
          v-model="system_field.records[scope.$index].fieldRuleType"
          placeholder="请输入内容"
          maxlength="100"
          minlength="1"
        />
      </template>
      <template slot="slot-description" slot-scope="scope">
        <span v-if="scope.$index < 12">{{ scope.row.description }}</span>
        <el-input
          v-if="scope.$index > 11"
          :ref="system_field.records[scope.$index].description"
          v-model="system_field.records[scope.$index].description"
          placeholder="请输入内容"
          maxlength="20"
          :class="{ 'input-selected': false }"
        />
      </template>
      <template slot="slot-required" slot-scope="scope">
        <span v-if="scope.$index < 10">必填</span>
        <span v-if="scope.$index == 10">选填</span>
        <span v-if="scope.$index == 11">-</span>
        <el-select
          v-if="scope.$index > 11"
          :ref="system_field.records[scope.$index].required"
          v-model="system_field.records[scope.$index].required"
          placeholder="请选择"
        >
          <el-option :key="1" :label="'必填'" :value="1" />
          <el-option :key="0" :label="'选填'" :value="0" />
        </el-select>
      </template>

      <template slot="operate-column" slot-scope="scope">
        <span v-if="scope.row.notFromInterface">-</span>
        <!-- <tableButton
          v-if="!scope.row.notFromInterface"
          :row="scope.row"
        /> -->
        <span v-if="!scope.row.notFromInterface">
          <el-button
            size="mini"
            @click="moveProTableData(scope.$index, scope.$index - 1)"
            >上移</el-button
          >
          <el-button
            size="mini"
            @click="moveProTableData(scope.$index, scope.$index + 1)"
            >下移</el-button
          >
          <el-button size="mini" @click="deleteProTableData(scope)"
            >删除</el-button
          >
        </span>
      </template>
    </h-table-list>

    <DownloadIdentify
      :visible.sync="dialogFormVisible"
      title="部门管理"
      @cancel="cancel"
      @update="dialogSubmit"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="ruleForm.realName" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone" />
        </el-form-item>
        <el-form-item label="归属部门" prop="organId">
          <el-input v-model="ruleForm.organId" />
        </el-form-item>
        <el-form-item label="职位" prop="positionsId">
          <el-input v-model="ruleForm.positionsId" />
        </el-form-item>
        <el-form-item label="账号类别" prop="userType">
          <el-input v-model="ruleForm.userType" />
        </el-form-item>
        <el-form-item label="登录账号" prop="userName">
          <el-input v-model="ruleForm.userName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" />
        </el-form-item>
      </el-form>
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import waves from "@/directive/waves"; // waves directive
import DownloadIdentify from "@/components/FormDialog";
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import ListOpearteButton from "@/components/AllButton/button2";
import tableButton from "@/components/AllButton/button3";
import data from "./const";
import constData from "@/utils/constData";
export default {
  name: "Device",
  components: {
    DownloadIdentify,
    Pagination,
    tableButton,
    ListOpearteButton,
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    return {
      selectOptions: [
        {
          value: "input",
          label: "单行文本框",
        },
        {
          value: "inputNumber",
          label: "单行纯数字(整数)",
        },
        {
          value: "inputFloat",
          label: "单行纯数字（小数）",
        },
        {
          value: "select1",
          label: "单级下拉框",
        },
        {
          value: "datePicker1",
          label: "时间选择框",
        },
        {
          value: "organization",
          label: "组织架构选择框",
        },
      ],
      selectDateOptions: [
        // {
        //   value: "YYYY-MM-DD HH:mm",
        //   label: "分",
        // },
        {
          value: "date",
          label: "天",
        },
        {
          value: "month",
          label: "月",
        },
        {
          value: "year",
          label: "年",
        },
      ],
      dialogFormVisible: false,
      loadList: false,
      tableData: constData,
      ruleForm: {
        userName: "",
        userType: "",
        enable: "",
        password: "",
        realName: "",
        phone: "",
        organId: "",
        positionsId: "",
      },
      rules: {
        userName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        realName: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
      },
      password: [
        {
          required: true,
          message: "密码6-20位，包含字母、数字、符号中至少两种，字母区分大小写",
          trigger: "blur",
        },
      ],
      paginationInfo: {
        sizeChange: (e) => {
          console.log(e);
        },
        currentChange: (e) => {
          this.$store.dispatch("system_field/setListSearchParams", {
            current: e,
          });
          this.getList(
            Object.assign({}, this.$store.state.system_field.listSearchParams)
          );
        },
        current: 1,
        total: 10,
      },
      formOptions: {
        inline: true,
        submitBtnText: "新增字段",
        showResetBtn: true,
        resetBtnText: "保存",
        searchParamsHandler: (params) => {
          console.log("查询");
          if (this.$store.state.system_field.records.length < 30) {
            const e = {
              description: "",
              fieldCode: "",
              fieldName: "",
              fieldRule: "",
              fieldRuleType: "",
              fieldType: "",
              required: "",
              tenantId: "",
              disabled: 1,
            };
            this.$store.dispatch("system_field/addOneListData", e);
          } else {
            this.$message("最多只能配置30个字段");
          }

          // this.getList(this.$store.state.system_field.listSearchParams);
        },
        changevalue: (params) => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)
          // console.log(params);
          // this.$store.dispatch("system_field/setListSearchParams", params);
        },
        resetBtnCallback: () => {
          this.update();
        },
        forms: [],
      },
      columns: [
        { type: "index", prop: "empno", label: "字段ID", width: 100 },

        {
          prop: "fieldName",
          label: "字段名称",
          width: 180,
          slotName: "slot-fieldName",
          renderHeader: this.renderHeader1,

          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: "fieldType",
          label: "字段类型",
          width: 180,
          slotName: "slot-fieldType",
          renderHeader: this.renderHeader2,
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.deviceNumber ? deviceInfo.deviceNumber :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        {
          prop: "fieldRuleType",
          label: "字段规则",
          minWidth: 180,
          slotName: "slot-fieldRuleType",
          renderHeader: this.renderHeader3,
        },
        {
          prop: "description",
          label: "提示语",
          minWidth: 180,
          slotName: "slot-description",
        },
        // {
        //   prop: "itemsSum",
        //   label: "点检项",
        //   slotName: "items-sum",
        //   minWidth: 180,
        // },
        {
          prop: "required",
          label: "必填/选填",
          minWidth: 180,
          slotName: "slot-required",
        },

        {
          prop: "operate",
          label: "操作",
          minWidth: 200,
          slotName: "operate-column",
          fixed: "right",
        },
      ],
    };
  },

  watch: {
    formChange: () => {},
  },
  computed: {
    ...mapState(["system_field", "app"]),
  },
  created() {
    // 初始获取几个基本数据,分别为操作状态,按钮权限等
    (this.formOptions.forms = this.formOptions.forms.map((e) => {
      const key = e.prop;
      const data = this.$store.state.system_field.listSearchParams;
      e.defaultValue = data[key] || "";
      return e;
    })),
      // this.submitHandler=this.searchWithParams
      this.$store
        .dispatch(this.$store_url_button, {
          add: this.add,
          export: this.export,
          delete: this.delete,
          edit: this.edit,
          detail: this.detail,
          using: this.using,
          useless: this.useless,
          downloadTemplete: this.downloadTemplete,
          downloadIdentify: this.downloadIdentify,
        })
        .then(async () => {
          // await this.$store.dispatch("app/getCodeList", []); //code转码
          this.getList(); // 表格数据
        });

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
    renderHeader1(h, { column, $index }, index) {
      return h("span", {}, [
        h("span", {}, "字段名称"),
        h(
          "el-popover",
          {
            props: {
              placement: "top-start",
              width: "200",
              trigger: "hover",
              content: `字段名称1-20字`,
            },
          },
          [h("i", { slot: "reference", class: "el-icon-info" }, "")]
        ),
      ]);
    },
    renderHeader2(h, { column, $index }, index) {
      return h("span", {}, [
        h("span", {}, "字段类型"),
        h(
          "el-popover",
          {
            props: {
              placement: "top-start",
              width: "200",
              trigger: "hover",
              content: `1.【单行文本框】：可输入文字、数字、符号

2.【单行纯数字（整数）文本框】：只可输入整数数字

3.【单行纯数字（小数）文本框】：只可输入数字，最多支持两位小数

4.【单级下拉框】：可预置单选选项

5.【时间选择框】：可用日历插件选择时间

7.【组织架构选择框】：可按本企业组织架构选择`,
            },
          },
          [h("i", { slot: "reference", class: "el-icon-info" }, "")]
        ),
      ]);
    },
    renderHeader3(h, { column, $index }, index) {
      return h("span", {}, [
        h("span", {}, "字段规则"),
        h(
          "el-popover",
          {
            props: {
              placement: "top-start",
              width: "200",
              trigger: "hover",
              content: `1.【单行文本框】：最大支持100位长度

2.【单行纯数字（整数）文本框】：最大支持10位长度

3.【单行纯数字（小数）文本框】：最大支持10位长度（不含小数点后位数）

4.【单级下拉框】：最大支持20个选项，用英文“,“区分

5.【时间选择框】：可配置选择精度

6.【组织架构选择框】：—`,
            },
          },
          [h("i", { slot: "reference", class: "el-icon-info" }, "")]
        ),
      ]);
    },
    moveProTableData(from, to) {
      console.log(from, "+++from+++");
      console.log(to, "++++to+++");

      const records = this.$store.state.system_field.records;
      console.log(records, "+++records++");

      // 检测移动边界
      if (to < 12 || to > records.length - 1) {
        return;
      }
      // 移动元素
      const moveTarget = records.splice(from, 1)[0];
      console.log(moveTarget, "++moveTarget+++");
      records.splice(to, 0, moveTarget);
      console.log(records, "+++after records+++");

      this.$store.dispatch("system_field/moveDeviceInfo", records);
    },

    deleteProTableData(row) {
      console.log(row, "+++++row++++");

      this.$store.dispatch("system_field/deleteDeviceInfo", row);
    },

    cancel() {
      this.dialogFormVisible = false;
    },
    dialogSubmit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$store
            .dispatch("system_field/saveInfo", this.ruleForm)
            .then((res) => {
              this.getList();

              this.dialogFormVisible = false;
            })
            .catch((err) => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 自定义该业务模块下的按钮方法
    using(row) {
      this.$store
        .dispatch("system_field/useUserInfo", row.id)
        .then((res) => {
          this.getList();
          // this.dialogFormVisible=false
        })
        .catch((err) => {});
    },
    useless(row) {
      this.$store
        .dispatch("system_field/uselessUserInfo", row.id)
        .then((res) => {
          this.getList();
          // this.dialogFormVisible=false
        })
        .catch((err) => {});
    },
    add(row) {
      console.log(row);
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.ruleForm = row;
      this.dialogFormVisible = true;
    },
    downloadIdentify(row) {
      console.log("下载设备标识卡");
      this.dialogFormVisible = true;
    },
    async downloadTemplete(ids) {
      console.log("下载导出模板");
      const download = await this.$store.dispatch(
        "system_field/downloadTemplete"
      );
      // window.open(download.)
      console.log(download);
    },
    delete(row) {
      console.log(row);
      this.$store.dispatch("system_field/deleteDeviceInfo", row); // 前端删除
    },
    update() {
      // 直接由vuex处理
      this.$store
        .dispatch("system_field/saveInfo")
        .then((res) => {
          // this.$message({
          //   message: res.mesg,
          //   type: "success",
          // });
          this.getList();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    detail(row) {
      console.log(row);

      localStorage.setItem("/device-basic/component/detail/index", row.id);
      this.$router.push("/device-basic/component/detail/index");
    },
    import() {},
    export() {
      console.log("导出");
      this.$store.dispatch("system_field/exportFile");
    },
    // 弹窗的关闭
    cancel() {
      console.log("关闭弹窗");
      this.dialogFormVisible = false;
    },
    // 更新弹窗数据
    updateDialog() {
      console.log("更新并关闭弹窗");
      this.dialogFormVisible = false;
    },
    // 搜索按钮
    searchWithParams() {
      console.log("查询");
    },
    getList(args) {
      console.log("getList", args);
      this.$store
        .dispatch("system_field/requestFieldList", args)
        .then(
          this.$set(this, "tableData", this.$store.state.system_field.records)
        );
    },
    handleFilter(args) {
      this.listQuery.page = 1;
      this.getList(args);
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作成功",
        type: "success",
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: "",
      };
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleDelete(row) {
      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000,
      });
      const index = this.list.indexOf(row);
      this.list.splice(index, 1);
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
  },
};
</script>
<style scoped>
.input-selected input.el-input__inner {
  border: 2px solid red;
}
</style>
